package org.rqb.dialog;

import lombok.Data;
import org.rqb.timer.MyTimer;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static org.rqb.Constant.DEFAULTDATETIMEFORMATTER;

@Data
public class TaskListDialog {

    private final JFrame parentFrame;
    private final DefaultListModel<String> listModel;
    private final JList<String> taskList;
    private final List<Timer> tasks = new ArrayList<>();

    public TaskListDialog(JFrame parentFrame) {
        this.parentFrame = parentFrame;

        listModel = new DefaultListModel<>();
        taskList = new JList<>(listModel);

        //填充数据
        updateListModel();
    }

    /** 弹出任务列表窗口 */
    public void showDialog() {
        JDialog dialog = new JDialog(parentFrame, "待执行任务列表", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(parentFrame);

        // 任务列表面板
        JPanel listPanel = new JPanel(new BorderLayout());
        taskList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(taskList);
        listPanel.add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));
        JButton deleteBtn = new JButton("取消选中任务");
        JButton closeBtn = new JButton("关闭");

        deleteBtn.addActionListener(e -> deleteSelectedTask());
        closeBtn.addActionListener(e -> dialog.dispose());

        buttonPanel.add(deleteBtn);
        buttonPanel.add(closeBtn);

        dialog.setLayout(new BorderLayout());
        dialog.add(listPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        dialog.setVisible(true);
    }

    /**
     * 添加任务
     * @param timer
     */
    public void addTask(Timer timer) {
        tasks.add(timer);
        updateListModel();
    }

    public void removeTask(Timer timer) {
        tasks.remove(timer);
        updateListModel();
    }


    /** 删除选中的任务 */
    private void deleteSelectedTask() {
        int index = taskList.getSelectedIndex();
        if (index != -1) {
            Timer delTimer = tasks.remove(index);
            delTimer.cancel();
            updateListModel();
        } else {
            JOptionPane.showMessageDialog(parentFrame, "请先选择要删除的任务", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    /** 更新 JList 显示内容 */
    private void updateListModel() {
        listModel.clear();

        for (Timer timer : tasks) {
            if (!(timer instanceof MyTimer)){
                continue;
            }
            MyTimer myTimer = (MyTimer) timer;

            listModel.addElement("记录名称：" + myTimer.getTimerName() + "  记录时间：" + myTimer.getRecodeDateTime().format(DEFAULTDATETIMEFORMATTER) );
        }
    }


}
